<?php
/*
 * This file is part of the BooXtore Student project.
 *
 * (c) Francis Backeland f.backeland@gmail.com
 * (c) Laurine Chaplot chaplot.laurine@orange.fr
 * (c) Julien Dutot julien.dutot@gmail.com
 * (c) Romain Guillaume romain-guillaume@orange.fr
 * (c) Guillaume Paringaux g.paringaux@gmail.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 */

namespace BXTR\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use BXTR\UserBundle\Entity\Role;
use Symfony\Component\HttpFoundation\Request;

/**
 * Role managment 
 */
class RoleController extends Controller
{
    /** 
     * Display a list of roles 
     */
    public function listAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $roles = $em->getRepository('BXTRUserBundle:Role')
            ->findAll();

        $form = $this->createFormBuilder()
            ->add('list', 'datatables_selector', Array(
                'collection' => $roles,
                'fields' => Array('role', 'label'),
                'labels' => Array('Ent.Default.Fields.name', 'Ent.Default.Fields.label'),
                'index_field' => 'role'
            ))
            ->add('back', 'back_button', array(
                'url' => $this->generateUrl('bxtr_admin_index')
            ))
            ->add('add', 'add_button')
            ->add('delete', 'remove_button', array(
                'datatables_selector' => true,
            ))
            ->add('edit', 'edit_button', array(
                'datatables_selector' => true,
            ))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isValid()) {
            // test wich button is clicked and apply redirects
            if ($form->get('add')->isClicked()) {

                return $this->redirect($this->generateUrl('bxtr_admin_role_add'));
            } elseif ($form->get('edit')->isClicked()) {
                $selectedUser = $form->get('list')->getData();

                return $this->redirect($this->generateUrl('bxtr_admin_role_edit', Array('id' => $selectedUser->getRole())));
            } elseif ($form->get('delete')->isClicked()) {
                $selectedUser = $form->get('list')->getData();

                return $this->redirect($this->generateUrl('bxtr_admin_role_delete', Array('id' => $selectedUser->getRole())));
            }
        }
        
        // Display view
        $trans = $this->get('translator');
        return $this->render('BXTRAdminBundle:Layout:List.html.twig', Array(
            'form' => $form->createView(),
            'main_title' => $trans->trans('Ent.Role.List')
        ));
    }
    /** 
     * Display an role record.
     */
    public function addAction(Request $request) 
    {
        return $this->buildEditForm($request);
    }

    /**
     * Display a remove confirmation page.
     *
     * @param Request $request
     * @param mixed $id
     */
    public function deleteAction(Request $request, $id) 
    {
        // Fetch entities
        $em = $this->getDoctrine()->getManager();

        try {
            $role = $em->getRepository('BXTRUserBundle:Role')
                ->findOneByRole($id);
        } catch ( \Doctrine\ORM\NoResultException $e) {
            throw new \Exception("Unknown Id");
        }

        // Begin form building
        $builder = $this->createFormBuilder();
        
        $trans = $this->get('translator');

        // Message displayed by the view.
        $userCount = $role->getUsers()->count();
        $message = $trans->transchoice('Ent.Role.ConfirmDelete', $userCount, Array(
            '%name%' => $role->getRole(),
            '%nb_user%' => $userCount,
        ));

        $form = $builder
            ->add('delete', 'remove_button')
            ->add('back', 'back_button', array(
                'url' => $this->generateUrl('bxtr_admin_role_list')
            ))
            ->getForm();

        $form->handleRequest($request);

        if($form->isValid()) {
            if ($userCount > 0) {
                foreach( $role->getUsers() as $user) {
                    $user->setDbRole(NULL);
                }
            }
            $em->remove($role);
            $em->flush();

            return $this->redirect($this->generateUrl('bxtr_admin_role_list'));
        } 
        
        return $this->render('BXTRAdminBundle:Layout:Delete.html.twig', array(
            'form' => $form->createView(),
            'main_title' => $trans->trans('Ent.Role.Delete', Array('%name%' => $role->getLabel() )),
            'message' => $message,
        ));
    }

    /**
     * Display an edit form
     *
     * @param Request $request
     * @param mixed $id
     */
    public function editAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $role = $em->getRepository('BXTRUserBundle:Role')->findOneByRole($id);

        if (!$role) {
            throw new \Exception("Unknown Id");
        }
        
        return $this->buildEditForm($request, $role);
    }

    /**
     * Build the add or edit form.
     * A simple field list with a back and save button.
     *
     * @param Request $request
     */
    protected function buildEditForm(Request $request, Role $role=null) {
        // Indicate if it is and addition or edition form.
        $add = false;
        if ($role === null) {
            $role = new Role();
            $add = true;
        }

        $trans = $this->get('translator');
        $builder = $this->createFormBuilder($role)
            ->add('role', 'text', array(
                'label' => $trans->trans('Ent.Default.Fields.name')
            ))
            ->add('label', 'text', array(
                'label' => $trans->trans('Ent.Default.Fields.label')
            ));

        $form = $builder
            ->add('back', 'back_button', array(
                'url' => $this->generateUrl('bxtr_admin_role_list'),
            ))
            ->add('save', 'save_button')
            ->getForm();


        $form->handleRequest($request);

        if($form->isValid()) {
            if ($form->get('save')->isClicked()) {
                $em = $this->getDoctrine()->getManager();

                $em->persist($role);
                $em->flush();
            }
            return $this->redirect($this->generateUrl('bxtr_admin_role_list'));
        }

        $title = null;
        if ( $add ) {
            $title = $trans->trans('Ent.Role.AddNew');
        } else {
            $title = $trans->trans('Ent.Role.EditExisting', array('%name%' => $role->getLabel()));
        }

        return $this->render('BXTRAdminBundle:Layout:Edit.html.twig', array(
            'form' => $form->createView(),
            'main_title' => $title
        ));
    }
}
